package marco.android.CouchControl;

import java.io.ByteArrayOutputStream;
import android.content.Context;
import android.os.Build;
import android.util.Log;

public abstract class Connection
{
	private static final String TAG = "CouchControll::Connection";
	public enum IOMode { eNone, eWiFi, eBluetooth };
	
	protected static Object sLock = new Object();
	protected String mServerAddress = null;
	protected int mPort = -1;
	
	protected Thread mConnectionThread = null;
	protected Event mEvent = new Event();
	protected ByteArrayOutputStream mByteStream = new ByteArrayOutputStream();
	NetworkIO mNetIO = new NetworkIO(mByteStream);
	
	public interface ConnectionListener
	{
		public void StartBluetoothActivityForResult(); 
		public void StartWiFiActivityForResult();
		public void UpdateConnectionStatus(String host);
	}
	
	ConnectionListener mListener;
	
	public static Connection Instance(Context context, IOMode mode,
									  ConnectionListener listener)
	{
		final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
		Connection connection = null;		
		
		if(sdkVersion < Build.VERSION_CODES.DONUT)
		{
			connection = new TCPClient();
		}
		else
		{
			if(mode == IOMode.eBluetooth)
			{
			   connection = new BluetoothClient();
			}
			else
			{
				connection = new TCPClient();
			}
		}
		
		connection.mListener = listener;

		Log.d(TAG, "Created new " + connection.getClass());

		return(connection);
	}
	
	public abstract IOMode GetMode();
	public abstract void Initialize(String address, Integer port);
	public abstract void Start();
	public abstract void Stop();
	
	public void SendEvent(Event e)
	{
		synchronized(sLock)
		{
			mEvent = e;
			sLock.notify();
		}
	}
}
